{% extends "base.html" %}

{% block title %}行情 - 恐慌指数{% endblock %}

{% block extra_css %}
    <style>
        .container {
            width: 90%;
            margin: 20px auto;
        }
        .chart-container {
            width: 100%;
            height: 600px;
            border: 1px solid #eee;
            border-radius: 8px;
            margin-bottom: 30px;
        }
        .chart-title {
            text-align: center;
            font-size: 18px;
            font-weight: bold;
            margin: 10px 0;
        }
        .info-text {
            text-align: center;
            color: #666;
            margin: 20px 0;
        }
        .time-range-selector {
            text-align: center;
            margin: 15px 0;
        }
        .time-range-selector label {
            font-weight: bold;
            margin-right: 10px;
        }
        .time-range-btn {
            padding: 8px 15px;
            margin: 0 5px;
            border: 1px solid #ccc;
            background-color: #f8f9fa;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }
        .time-range-btn:hover {
            background-color: #e9ecef;
        }
        .time-range-btn.active {
            background-color: #007bff;
            color: white;
            border-color: #007bff;
        }
    </style>
{% endblock %}

{% block content %}
    <div class="container">
        <div class="chart-title">A股恐慌指数历史走势</div>
        <div class="info-text">
            <p>恐慌指数反映市场情绪，数值越高表示市场越恐慌，数值越低表示市场越贪婪</p>
        </div>
        <div class="time-range-selector">
            <label>时间范围：</label>
            <button class="time-range-btn active" data-range="1m">1个月</button>
            <button class="time-range-btn" data-range="3m">3个月</button>
            <button class="time-range-btn" data-range="1y">1年</button>
            <button class="time-range-btn" data-range="3y">3年</button>
            <button class="time-range-btn" data-range="all">全部</button>
        </div>
        <div id="sentimentChart" class="chart-container"></div>
    </div>
{% endblock %}

{% block extra_js %}
    <script src="{{ url_for('static', filename='js/echarts.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/jquery.min.js') }}"></script>
    <script type="text/javascript">
        console.log("jQuery是否加载成功：", typeof $ !== "undefined");
        console.log("ECharts是否加载成功：", typeof echarts !== "undefined");

        // 初始化图表
        const sentimentChart = echarts.init(document.getElementById('sentimentChart'));

        // 从API获取数据并渲染图表
        function loadChartData(timeRange = '1m') {
            $.ajax({
                url: '/api/market/sentiment',
                type: 'GET',
                data: { range: timeRange },
                dataType: 'json',
                success: function(response) {
                    if (!response.success) {
                        alert(`数据加载失败：${response.error}`);
                        return;
                    }
                    
                    renderSentimentChart(sentimentChart, response.data);
                },
                error: function(xhr, status, error) {
                    alert(`请求失败：${error}`);
                    console.error("AJAX错误：", status, error);
                    console.error("后端返回：", xhr.responseText);
                }
            });
        }

        // 初始加载默认时间范围的数据
        loadChartData('1m');

        // 处理时间范围按钮点击事件
        $('.time-range-btn').on('click', function() {
            // 移除所有按钮的active类
            $('.time-range-btn').removeClass('active');
            // 为当前点击的按钮添加active类
            $(this).addClass('active');
            
            // 获取时间范围并重新加载数据
            const timeRange = $(this).data('range');
            loadChartData(timeRange);
        });

        function renderSentimentChart(chart, data) {
            // 提取日期和收盘价数据
            const dates = data.map(item => item.date);
            const closePrices = data.map(item => item.close);
            
            const option = {
                title: {
                    text: 'A股恐慌指数历史走势',
                    left: 'center',
                    textStyle: { fontSize: 16 }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { type: 'line' },
                    formatter: function(params) {
                        const param = params[0];
                        return `<div>日期：${param.name}</div>
                                <div>恐慌指数：${param.value.toFixed(2)}</div>`;
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: dates,
                    axisLabel: {
                        rotate: 45,
                        interval: Math.ceil(dates.length / 20)
                    },
                    splitLine: { show: false }
                },
                yAxis: {
                    type: 'value',
                    name: '恐慌指数',
                    axisLabel: {
                        formatter: '{value}'
                    }
                },
                series: [
                    {
                        name: '恐慌指数',
                        type: 'line',
                        data: closePrices,
                        smooth: true,
                        lineStyle: { color: '#e74c3c', width: 2 },
                        symbol: 'none',
                        areaStyle: {
                            color: '#fadbd8'
                        }
                    }
                ]
            };

            chart.setOption(option);
        }

        window.addEventListener('resize', function() {
            sentimentChart.resize();
        });
    </script>
{% endblock %}